package com.romotc.qqrobot.bean;

import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import com.romotc.qqrobot.webqq.qqInterfaceCall.Add_need_verify2_InterCall;
import com.romotc.qqrobot.webqq.qqInterfaceCall.Change_mark_name2_InterCall;
import com.romotc.qqrobot.webqq.qqInterfaceCall.Get_friend_uin2_GetQQNumFromTuin_InterCall;
import com.romotc.qqrobot.webqq.qqInterfaceCall.Search_qq_by_uin2_InterCall;
import com.romotc.qqrobot.webqq.qqInterfaceCall.dataProcessor.DateProcessor;
import com.romotc.qqrobot.webqq.qqInterfaceCall.dataProcessor.Get_friend_uin_CheckFriendAndCustomerProcess;
import com.romotc.scache.RequestSpy;

/**
 * QQ任务
 * @author Administrator
 *
 */
public class QQTaskService {

	private static QQTask qryInstance = new QQTask();
	/**
	 * 增加一项QQ任务：
	 * 这里只是入库
	 * 检查Qq好友与客户的对象关系
	 * 如果Qq好友的markName为空则取QQ号码 然后增加相应客户
	 * 如果markName不为空(有可能重复)：取QQ号码，检查Qq号码是否存在客户
	 * @param friend
	 * @param curQQ
	 */
	public static void addTask_checkQFriendCustomer(QQUserFriend friend,
			QQLogedin curQQ) {
		if(friend == null || curQQ == null)
			return;
		
		QQTask qTask = new QQTask();
		qTask.setLoginId(curQQ.getId());
		qTask.setTaskQqNum(curQQ.getUin());
		qTask.setTaskQqUin(friend.getUin());
		qTask.setTaskType(QQTask.TaskType_CheckFriendAndCustomer);
		qTask.Save();
	}

	/**
	 * 运行任务
	 * @param curQq
	 */
	public static void runTask(QQLogedin curQq) {
		List<QQTask> taskList = qryAllUnFinishedTasks(curQq);
		
		if(taskList != null && !taskList.isEmpty()) {
			for(QQTask qTask : taskList) {
				runTask(qTask, curQq);
				try {
					Thread.sleep(2000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * 执行一项任务
	 * @param task
	 * @param curQq
	 */
	public static void runTask(QQTask task, QQLogedin curQq) {
		if(task == null || curQq == null)
			return;
		try {
			if(QQTask.TaskType_CheckFriendAndCustomer.equals(task.getTaskType()))
			{
				//检查好友 与 客户对应关系
				Get_friend_uin2_GetQQNumFromTuin_InterCall getQNumCall = Get_friend_uin2_GetQQNumFromTuin_InterCall.getInstance();
				JSONObject reqData = new JSONObject();
				
					reqData.put(getQNumCall.Key_Must_Input_Tuin, task.getTaskQqUin());
					
					task.setTaskRunTime();
					reqData.put(Get_friend_uin_CheckFriendAndCustomerProcess.QQTaskObject, task);
					reqData = getQNumCall.call(curQq, reqData,
							Get_friend_uin_CheckFriendAndCustomerProcess.getInstance());
					
				
			}else if(QQTask.TaskType_AddFriends.equals(task.getTaskType())) {
				//加好友已知QQ号码
				
				//调用Add_need_verify2_InterCall加好友
				Add_need_verify2_InterCall addCall = Add_need_verify2_InterCall.getInstance();
				JSONObject reqDataObj = new JSONObject();
				reqDataObj.put(addCall.Key_Input_Tuin, task.getTaskQqNum2());
				addCall.call(curQq, reqDataObj, new DateProcessor(){


					@Override
					public JSONObject processResponse(QQLogedin loginQQ,
							RequestSpy rqSpy, JSONObject reqDataObj)
							throws Exception {
						/**
						 *正常的返回：{"retcode":0,"result":{"result":0}} 修改customer表
						 *请求数据格式错误：{"retcode":100001}
						 *请求过于频繁：{"retcode":100003} 对任何号码的加好友申请都会屏蔽
						 */
						// nomal response:{"retcode":0,"result":{"result":0}}
						String res = rqSpy.getResBody();
						if(res != null && res.indexOf("\"result\":0") != -1) {
							reqDataObj.put(Key_RetCode, "Ok");
						}else {
							reqDataObj.remove(Key_RetCode);
							reqDataObj.put(DateProcessor.Key_ResBody, res);
						}
						return reqDataObj;
					}
					
				});
				
				if("Ok".equals(reqDataObj.opt(DateProcessor.Key_RetCode))) {
					task.setTaskRunResult(task.RunResult_Finished);
				}else {
					task.setTaskRunResult(task.RunResult_Error_DotTry);
				}
				
				task.setTaskRunNote(reqDataObj.optString(DateProcessor.Key_ResBody,""));
				
			}else if(QQTask.TaskType_ChgMarkName.equals(task.getTaskType())) {
				//修改好友昵称 chg markName
				Change_mark_name2_InterCall chgMarkNameCall = Change_mark_name2_InterCall.getInstance();
				JSONObject reqDataObj = new JSONObject();
				
				reqDataObj.put(chgMarkNameCall.Key_Input_Markname, task.getContent());
				reqDataObj.put(chgMarkNameCall.Key_Must_Input_Tuin, task.getTaskQqUin());
				task.setTaskRunTime();
				
				chgMarkNameCall.call(curQq, reqDataObj, new DateProcessor(){

					@Override
					public JSONObject processResponse(QQLogedin loginQQ,
							RequestSpy rqSpy, JSONObject reqDataObj)
							throws Exception {
						// nomal response:{"retcode":0,"result":{"result":0}}
						String res = rqSpy.getResBody();
						if(res != null && res.indexOf("\"result\":0") != -1) {
							reqDataObj.put(Key_RetCode, "Ok");
						}else {
							reqDataObj.remove(Key_RetCode);
							reqDataObj.put(DateProcessor.Key_ResBody, res);
						}
						return reqDataObj;
					}
					
				});

				if("Ok".equals(reqDataObj.opt(DateProcessor.Key_RetCode))) {
					task.setTaskRunResult(task.RunResult_Finished);
				}else {
					task.setTaskRunResult(task.RunResult_Error_DotTry);
				}
				
				task.setTaskRunNote(reqDataObj.optString(DateProcessor.Key_ResBody,""));
				
			}
		
		} catch (JSONException e) {
			task.setTaskRunNote(e.getMessage());
			task.setTaskRunResult(task.RunResult_Error_DotTry);
			
			e.printStackTrace();
		} catch (Exception e) {
			task.setTaskRunNote(e.getMessage());
			task.setTaskRunResult(task.RunResult_Error_DotTry);
			e.printStackTrace();
		}finally{
			task.Delete();
			task.Save();
		}
		
	}

	/**
	 * 查询制定QQ号的所有未完成的任务列表
	 * @param curQq
	 * @return 按照taskId升序排列 最多20个
	 */
	public static List<QQTask> qryAllUnFinishedTasks(QQLogedin curQq) {
		long loginId = curQq.getId();
		String filter = "taskQqNum = '" + curQq.getUin() 
			+ "' and (loginId = " + loginId + " or loginId = 0)"
			+ " and (taskRunResult is null or taskRunResult = 0 or taskRunResult = " + QQTask.RunResult_NeedReTry + ")";
		int size = qryInstance.TotalCount(filter);
		if(size == 0)
			return null;
		
		List<QQTask> taskList = (List<QQTask>)qryInstance.FilterOrderBy(filter, 
				"id ASC", 1, size > 20 ? 20 : size);
		return taskList;
	}
	
	public static void main(String[] args) {
		QQLogedin curq = new QQLogedin();
		curq.setUin(""+97190865);
		curq.setId(706);
		List<QQTask> taskList = qryAllUnFinishedTasks(curq);
		if(taskList != null && !taskList.isEmpty()) {
			for(QQTask task : taskList) 
				System.out.println(task.getId());
		}
	}
}
